/*
 * 版权所有 (C) 2001-2014 深圳市艾派应用系统有限公司。保留所有权利。
 * 版本：
 * 修改记录：
 *		1、2014-11-25，tfl创建。 
 */
package com.chinamobile.ln.ictenterprises.ui.fragment;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.chinamobile.ln.ictenterprises.R;
import com.chinamobile.ln.ictenterprises.common.Config;
import com.chinamobile.ln.ictenterprises.common.Constants;
import com.chinamobile.ln.ictenterprises.common.Controller;
import com.chinamobile.ln.ictenterprises.common.GlobalSetting;
import com.chinamobile.ln.ictenterprises.http.HttpAsyncTask;
import com.chinamobile.ln.ictenterprises.model.Step;
import com.chinamobile.ln.ictenterprises.model.request.SearchHistory;
import com.chinamobile.ln.ictenterprises.model.response.ResponseHistory;
import com.chinamobile.ln.ictenterprises.model.response.ResponseHistory.Records;
import com.chinamobile.ln.ictenterprises.ui.activity.MsgDetailActivity;
import com.chinamobile.ln.ictenterprises.ui.adapter.TimerAdapter;
import com.chinamobile.ln.ictenterprises.utils.JsonUtil;
import com.chinamobile.ln.ictenterprises.utils.Utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

@SuppressLint("HandlerLeak")
public class TimerSendFragment extends Fragment implements OnItemClickListener
{
    private Context context;
    private TimerAdapter adapter;
    private ListView listView;
    private List<Records> listRecords = new ArrayList<Records>();
    private String timercurrPage = "1";
    private String timerallPage = "1";
    private Controller mHttpManager = null;
    private SharedPreferences sharedPref;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        context = getActivity();
        mHttpManager = Controller.getInstance();
        sharedPref = context.getSharedPreferences(Constants.LOGIN_SHAREDPREF,
            Context.MODE_PRIVATE);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState)
    {
        View view = inflater.inflate(R.layout.fragment_list_timer, null);
        listView = (ListView) view.findViewById(R.id.listView);
        return view;
    }

    @Override
    public void onResume()
    {
        super.onResume();
        timercurrPage = "1";
        getData(timercurrPage);
    }

    @Override
    public void onAttach(Activity activity)
    {
        super.onAttach(activity);

    }

    /**
     * 初始化定时中列表
     */
    private void getData(String currPage)
    {
        SearchHistory searchHistory = new SearchHistory(
            GlobalSetting.GET_FOR_PAGE, Constants.REQUEST_TYPE_TIMER, currPage);
        String params = JsonUtil.objectToJson(searchHistory);
        Step step = Utils.paramsUtil(Config.SEND_MSG, params);
        HttpAsyncTask httpAsyncTask = new HttpAsyncTask(step,
            HttpAsyncTask.CACHE_TYPE_ACTION, sharedPref.getString(
                Constants.COOKIES, ""), GlobalSetting.GET_HISTORY);
        httpAsyncTask.setUIHandler(getHistoryHandler);
        mHttpManager.execute(httpAsyncTask);
    }

    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg)
        {
            timercurrPage = String.valueOf(Integer.parseInt(timercurrPage) + 1);
            getData(timercurrPage);
        }
    };

    @SuppressLint("HandlerLeak")
    private Handler getHistoryHandler = new Handler() {

        @SuppressWarnings("unchecked")
        public void handleMessage(Message msg)
        {
            if (msg.obj != null)
            {
                Map<String, Object> httpMap = (Map<String, Object>) msg.obj;
                int reultCode = (Integer) httpMap
                    .get(GlobalSetting.STUATUS_CODE);
                if (reultCode == GlobalSetting.STUATUS_CODE_SUCCESS)
                {
                    ResponseHistory responseHistory = (ResponseHistory) httpMap
                        .get(GlobalSetting.JSON_HISTORY);
                    if (responseHistory != null)
                    {
                        if (responseHistory.resultFlag
                            .equals(GlobalSetting.RESULT_FLAG_SUC))
                        {
                            List<Records> list = responseHistory.results.records;
                            if (list.size() > 0 || list != null)
                            {
                                timercurrPage = responseHistory.results.page;
                                timerallPage = responseHistory.results.totalPageCount;
                                if (timercurrPage.equals("1"))
                                {
                                    listRecords = list;
                                }
                                else
                                {
                                    listRecords.addAll(list);
                                }
                            }
                            setView();
                        }
                        else if (responseHistory.resultFlag
                            .equals(GlobalSetting.RESULT_FLAG_FAIL))
                        {
                            Toast.makeText(context, R.string.get_timer_fail,
                                Toast.LENGTH_SHORT).show();
                        }
                    }
                    else
                    {
                        Toast.makeText(context, R.string.get_timer_fail,
                            Toast.LENGTH_SHORT).show();
                    }
                }
            }
        };
    };

    public void setView()
    {
        if (adapter == null)
        {
            adapter = new TimerAdapter(context, listRecords, handler,
                timercurrPage, timerallPage);
            listView.setAdapter(adapter);
            listView.setOnItemClickListener(this);
        }
        else
        {
            adapter.list = listRecords;
            adapter.currPage = timercurrPage;
            adapter.allPage = timerallPage;
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
        long arg3)
    {
        Records records = (Records) listView.getAdapter().getItem(position);
        String content = records.msg;
        String time = records.time;
        String addressList = records.addressList;
        Intent intent = new Intent();
        intent.putExtra("content", content);
        intent.putExtra("time", time);
        intent.putExtra("addressList", addressList);
        intent.setClass(getActivity(), MsgDetailActivity.class);
        startActivity(intent);
    }
}
